package com.centriole.service.workflow.service.impl;

import com.centriole.service.workflow.dao.ProNodeMapper;
import com.centriole.service.workflow.entity.ProNode;
import com.centriole.service.workflow.enums.FlowNode;
import com.centriole.service.workflow.service.NoticeService;
import com.centriole.service.workflow.service.ProNodeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProNodeServiceImpl implements ProNodeService {

	@Resource
	private ProNodeMapper proNodeMapper;
	@Resource
	private NoticeService noticeService;
	
	public void insertNode(ProNode proNode) {
//		List<ProNode> list = proNodeMapper.selectByProcessId(proNode.getProcessId());
//		if(CommonUtil.isNotEmpty(list)){
//			proNodeMapper.deleteByProcessId(proNode.getProcessId());
//		}
		proNodeMapper.insertNode(proNode);
	}

	public void logicDeleteByProcessId(String processId) {
		proNodeMapper.logicDeleteByProcessId(processId);
		//通知表
		noticeService.logicDeleteByProcessId(processId);
	}

	public void deleteByProcessId(String processId) {
		proNodeMapper.deleteByProcessId(processId);
		//通知表
		noticeService.deleteByProcessId(processId);
	}

	public List<ProNode> selectByProcessId(String processId) {
		List<ProNode> list = proNodeMapper.selectByProcessId(processId);
		return list;
	}

	public ProNode selectById(String id) {
		ProNode p = proNodeMapper.selectById(id);
		return p;
	}

	/**
	 *	获取一个节点的顺序下标 ， 与用户在前端页面 添加节点的顺序有关，哪个节点被先添加，哪个节点的顺序下标就小
	 * @param code
	 * @return
	 */
	private int getNodeIndex(ProNode code){
		try {
			return Integer.valueOf( code.getCode().split("-")[0].split("_")[2]  );
		}catch (Exception e){
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 2018/05/17新增：
	 * 【在调用该方法前，要确保该节点是一个“审批”节点 ，
	 * 	确保所有节点的code字段为 " demo_node_4-multiTaskOrChild" 、 "demo_node_2-userTask" 类似形式的字符串】
	 * 判断该节点是否是 最后一个审批节点
	 * @param node	ProNode
	 * @return	true表示 是 ； false表示不是
	 */
	public boolean isLastExamineNode(ProNode node){
		ProNode lastExamineNode = selectByProcessId(node.getProcessId()).parallelStream().filter(e -> e.getCode().contains(FlowNode.EXAMINE))
				.sorted((e1, e2) -> getNodeIndex(e1) - getNodeIndex(e2)).collect(Collectors.toList()).get(0);
		return node.getCode().equals(lastExamineNode.getCode()) ;
	}

}
